package service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

import JDBC.DBUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import method.AccountReleaseInformation;
import method.ItemInformation;
import net.sf.json.JSONObject;
/**
 * @author Gao Shiwei
 * user can scan all items they have published
 */
@WebServlet(name = "SearchMyAllItem")
public class SearchMyAllItem extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        HttpSession session=request.getSession();
        String PhoneNumber=(String)session.getAttribute("PhoneNumber");

        JsonObject Container=new JsonObject();

        com.google.gson.JsonArray array=new JsonArray();

        JsonObject oneItem=new JsonObject();
        AccountReleaseInformation[] Release= DBUtils.QueryAccountReleaseInformation("PhoneNumber",PhoneNumber);
        for(int i=0;i<Release.length;i++){
            oneItem.addProperty("ItemID", Release[i].getItemID());
            System.out.println(Release[i].getItemID());
            ItemInformation[] Item=DBUtils.QueryItemInformation("ItemID",Release[i].getItemID());
            if (Item.length==0){
                continue;
            }
            oneItem.addProperty("ItemName",Item[0].getItemName());
            oneItem.addProperty("ItemPrice",Item[0].getItemPrice());
            oneItem.addProperty("ItemType",Item[0].getItemType());
            oneItem.addProperty("ItemQuantity",Item[0].getItemQuantity());
            oneItem.addProperty("ItemDescription",Item[0].getItemDescription());
            String picture=DBUtils.QueryItemPicture(Release[i].getItemID());
            if(picture!=null)
            picture.replace("\\","\\\\");
            oneItem.addProperty("Picture",picture);
            array.add(oneItem);
            oneItem=new JsonObject();
        }
        Container.add("Item",array);
        PrintWriter out = response.getWriter();
        out.println(Container);
        out.flush();
        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
